from pylint import lint
from pylint.reporters import JSONReporter
from dataclasses import dataclass, asdict
from io import StringIO
import json
from typing import List, Dict

@dataclass
class PylintMessage:
    type: str
    module: str
    obj: str    
    line: int
    column: int
    symbol: str
    message: str
    message_id: str

class PylintRunner:
    
    def __init__(self, path):
        self._path = path # 要检查的文件夹路径
        self._score = None
        self._output = None

    def run(self):
        #output_stream = StringIO()
        #reporter = JSONReporter(output_stream)
        options = [
            self._path,
            '--output-format=json',# 以 json 形式输出
            '--score=y',
            '--reports=y',
            '--recursive=y',
            '--disable=C,R',# 禁用代码风格检查和重构建议
        ]
        #lint.Run(options, reporter=reporter, exit=False)
        #self._output = output_stream.getvalue()
        #result = self.parse()
        #output_stream.close()
        lint.Run(options)
        return result

    # 将结果按文件名解析
    def parse(self):
        message = json.loads(self._output)
        files_dict: Dict[str, List[dict]] = {}
        for msg in message:
            pylint_msg = PylintMessage(
                type=msg.get('type', ''),
                module=msg.get('module', ''),
                obj=msg.get('obj', ''),
                line=msg.get('line', 0),
                column=msg.get('column', 0),
                symbol=msg.get('symbol', ''),
                message=msg.get('message', ''),
                message_id=msg.get('message-id', '')
            )
            file_path = msg.get('path', '').split('/')[-1]
            msg_json = json.dumps(asdict(pylint_msg), ensure_ascii=False)
            if file_path not in files_dict:
                files_dict[file_path] = msg_json
            else:
                files_dict[file_path] += f"\n{msg_json}"
        return files_dict


if __name__ == "__main__":

    examinater = PylintRunner("/Users/cxh/workdir/metagpt/workspace/game_2048/game_2048")
    result = examinater.run()
    print(result)

